#!/usr/bin/env python3
"""
数据库初始化脚本
"""

import sys
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent))

import asyncio
import logging

from sqlalchemy.sql.expression import text

from app.database.session import engine, AsyncSessionLocal
from app.models import Base
from app.models.system_config import SystemConfig

# 配置日志
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)


async def init_database() -> None:
    """初始化数据库"""
    try:
        # 创建数据库表
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)  # type: ignore[attr-defined]
        logger.info("数据库表创建成功")

        # 插入初始系统配置
        await init_system_configs()

        logger.info("数据库初始化完成")

    except Exception as e:
        logger.error(f"数据库初始化失败: {e}")
        raise


async def init_system_configs() -> None:
    """初始化系统配置"""
    try:
        # 在async with语句上直接添加pyright忽略注释
        async with AsyncSessionLocal() as session:  # type: ignore[attr-defined]
            try:
                # 检查是否已有配置
                result = await session.execute(text("SELECT COUNT(*) FROM system_configs"))
                count = result.scalar()

                if count and count > 0:
                    logger.info("系统配置已存在，跳过初始化")
                    return

                # 插入默认系统配置
                default_configs: list[SystemConfig] = []
                
                # 使用属性赋值方式创建SystemConfig对象
                config1 = SystemConfig()
                config1.config_key = "qrcode_expire_minutes"
                config1.config_value = "30"
                config1.description = "二维码过期时间（分钟）"
                config1.is_encrypted = False
                default_configs.append(config1)
                
                config2 = SystemConfig()
                config2.config_key = "max_visitors_per_day"
                config2.config_value = "100"
                config2.description = "每日最大访客数量"
                config2.is_encrypted = False
                default_configs.append(config2)
                
                config3 = SystemConfig()
                config3.config_key = "visitor_checkin_timeout"
                config3.config_value = "15"
                config3.description = "访客签到超时时间（分钟）"
                config3.is_encrypted = False
                default_configs.append(config3)
                
                config4 = SystemConfig()
                config4.config_key = "system_name"
                config4.config_value = "新易访内网系统"
                config4.description = "系统名称"
                config4.is_encrypted = False
                default_configs.append(config4)
                
                config5 = SystemConfig()
                config5.config_key = "company_name"
                config5.config_value = "示例公司"
                config5.description = "公司名称"
                config5.is_encrypted = False
                default_configs.append(config5)
                
                config6 = SystemConfig()
                config6.config_key = "admin_email"
                config6.config_value = "admin@example.com"
                config6.description = "管理员邮箱"
                config6.is_encrypted = False
                default_configs.append(config6)
                
                config7 = SystemConfig()
                config7.config_key = "audit_log_retention_days"
                config7.config_value = "90"
                config7.description = "审计日志保留天数"
                config7.is_encrypted = False
                default_configs.append(config7)

                session.add_all(default_configs)
                await session.commit()
                logger.info(f"成功插入 {len(default_configs)} 条系统配置")

            except Exception as e:
                await session.rollback()
                logger.error(f"初始化系统配置失败: {e}")
                raise
            finally:
                await session.close()

    except Exception as e:
        logger.error(f"初始化系统配置失败: {e}")
        raise


async def drop_database() -> None:
    """删除数据库（开发环境使用）"""
    try:
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.drop_all)  # type: ignore[attr-defined]
        logger.info("数据库表删除成功")

    except Exception as e:
        logger.error(f"数据库删除失败: {e}")
        raise


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="数据库管理脚本")
    parser.add_argument("--init", action="store_true", help="初始化数据库")
    parser.add_argument("--drop", action="store_true", help="删除数据库")
    parser.add_argument("--reset", action="store_true", help="重置数据库（删除后初始化）")

    args = parser.parse_args()

    if args.init:
        asyncio.run(init_database())
    elif args.drop:
        asyncio.run(drop_database())
    elif args.reset:
        asyncio.run(drop_database())
        asyncio.run(init_database())
    else:
        print("请指定操作: --init, --drop, 或 --reset")
